package cn.chinaunicom.sdsi.gacx.workflow.elecmanage.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONObject;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cn.chinaunicom.sdsi.frm.base.BaseService;
import cn.chinaunicom.sdsi.frm.sys.R;
import cn.chinaunicom.sdsi.frm.sys.entity.SysStaff;
import cn.chinaunicom.sdsi.gacx.projApply.entity.TravelApplyEntity;
import cn.chinaunicom.sdsi.gacx.workflow.elecmanage.service.ElecBusinessService;
import cn.chinaunicom.sdsi.upfc_demp.dzgh.entity.DzghApplyEntity;
import cn.chinaunicom.sdsi.upfc_demp.dzgh.service.DzghApplyService;
import cn.chinaunicom.sdsi.gacx.projApply.service.projApplyService;

@Controller("elecBusinessController")
@RequestMapping(value = "/elecBusiness")
public class ElecBusinessController extends BaseService {

	private final Log log = LogFactory.getLog(ElecBusinessController.class);

	/**
	 * 工作流任务相关的业务逻辑组件
	 */
	private ElecBusinessService elecBusinessService;

	@Autowired
	private DzghApplyService dzghApplyService;
	
	@Autowired
	private projApplyService projApplyService;

	/**
	 * 跳转至公共业务发起页面
	 * 
	 * @return 跳转路径
	 */
	@RequestMapping("/elecBusinessStart")
	public ModelAndView elecBusinessStart(ModelAndView mv) {
		log.info("跳转到业务页面模拟流程发起！");
		DzghApplyEntity bean = this.dzghApplyService.getSessionStaff();
		// 获取电子公函编码
		SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");// 设置日期格式
		String elec_id = "GHBH" + df.format(new Date()) + ((int) (Math.random() * 900) + 100);// new
																								// Date()为获取当前系统时间
		bean.setElec_id(elec_id);
		mv.addObject("bean", bean);
		mv.setViewName("gacx/workflow/elecmanage/elec_apply");
		return mv;
	}
	
	/**
	 * 跳转至公共业务发起页面
	 * 
	 * @return 跳转路径
	 */
	@RequestMapping("/elecPsptBusinessStart")
	public ModelAndView elecPsptBusinessStart(ModelAndView mv) {
		log.info("跳转到业务页面模拟流程发起！");
		DzghApplyEntity bean = this.dzghApplyService.getSessionStaff();
		// 获取电子公函编码
		SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");// 设置日期格式
		String elec_id = "GHBH" + df.format(new Date()) + ((int) (Math.random() * 900) + 100);// new
																								// Date()为获取当前系统时间
		bean.setElec_id(elec_id);
		mv.addObject("bean", bean);
		mv.setViewName("gacx/workflow/elecmanage/elec_apply_pspt");
		return mv;
	}

	/**
	 * 跳转至公共业务发起页面
	 * 
	 * @return 跳转路径
	 */
	@RequestMapping("/elecBusinessModify")
	public ModelAndView elecBusinessModify(DzghApplyEntity entity, ModelAndView mv, HttpServletRequest request) {
		String processInstanceId = request.getParameter("processInstanceId");
		System.out.println("print processInstanceId = " + processInstanceId);
		log.info("跳转到业务页面模拟流程发起！");
		log.info("跳转到电子公函修改页面");
		// entity.setElec_id("GHBH20170515163404320");
		entity.setProc_inst_id(processInstanceId);
		DzghApplyEntity bean = this.dzghApplyService.queryByPrimaryKey(entity);
		if (!"".equals(bean.getNum()))
			bean.setNum(bean.getNum().replace(",", ";"));
		// bean.setJybh("JYBH00001");
		
		String viewNext ="gacx/workflow/elecmanage/elec_apply_modify";
		if ("1".equals(bean.getSelectType())){
			viewNext ="gacx/workflow/elecmanage/elec_apply_modify_pspt";
		}
		mv.addObject("bean", bean);
		mv.setViewName(viewNext);
		return mv;
	}

	/**
	 * 跳转至流程办理的业务页面
	 * 
	 * @return 跳转路径
	 */
	@RequestMapping("/elecBusinessView")
	public ModelAndView elecBusinessView(DzghApplyEntity dzghApplyEntity, HttpServletRequest request) {
		String processInstanceId = request.getParameter("processInstanceId");
		String taskDefinitionKey = request.getParameter("taskDefinitionKey");
		System.out.println("print processInstanceId = " + processInstanceId);
		log.debug("print processInstanceId ===== " + processInstanceId);
		log.info("跳转到业务页面模拟流程发起！");
		dzghApplyEntity.setProc_inst_id(processInstanceId);
		JSONObject obj = new JSONObject();
		obj = dzghApplyService.getElecApplyInfoByElecId(dzghApplyEntity);
		
		String viewNext ="gacx/workflow/elecmanage/elec_apply_view";
		if ("1".equals(obj.getString("selectType"))){
			viewNext ="gacx/workflow/elecmanage/elec_apply_view_pspt";
		}
		log.debug("print viewNext ===== " + viewNext);
		ModelAndView mv = new ModelAndView();
		mv.setViewName(viewNext);
		mv.addObject("processInstanceId", processInstanceId);
		mv.addObject("taskDefinitionKey", taskDefinitionKey);
		mv.addObject("applyInfo", obj);
		return mv;
	}

	/**
	 * 跳转至流程已办理的业务页面
	 * 
	 * @return 跳转路径
	 */
	@RequestMapping("/elecBusinessDoneView")
	public ModelAndView elecBusinessDoneView(DzghApplyEntity dzghApplyEntity,HttpServletRequest request) {
		String processInstanceId = request.getParameter("processInstanceId");
		String taskDefinitionKey = request.getParameter("taskDefinitionKey");
		log.info("跳转到业务页面已经办理页面！" + processInstanceId);
		
		dzghApplyEntity.setProc_inst_id(processInstanceId);

		JSONObject obj = new JSONObject();
		obj = dzghApplyService.getElecApplyInfoByElecId(dzghApplyEntity);
		
		String viewNext ="gacx/workflow/elecmanage/elec_apply_view";
		if ("1".equals(obj.getString("selectType"))){
			viewNext ="gacx/workflow/elecmanage/elec_apply_view_pspt";
		}
		
		ModelAndView mv = new ModelAndView();
		mv.setViewName(viewNext);
		mv.addObject("processInstanceId", processInstanceId);
		mv.addObject("taskDefinitionKey", taskDefinitionKey);
		mv.addObject("viewType", "1");
		mv.addObject("applyInfo", obj);
		return mv;
	}

	/**
	 * 跳转至流程办理的业务自定义页面1
	 * 
	 * @return 跳转路径
	 */
	@RequestMapping("/businessTaskTab1")
	public ModelAndView businessTaskTab1() {

		ModelAndView mv = new ModelAndView();
		mv.setViewName("frm/workflow/sample/business-task-tab");
		mv.addObject("tabInfo", "自定义标签1");

		log.info("跳转到业务自定义标签1");
		return mv;
	}

	/**
	 * 跳转至流程办理的业务自定义页面2
	 * 
	 * @return 跳转路径
	 */
	@RequestMapping("/businessTaskTab2")
	public ModelAndView businessTaskTab2() {

		ModelAndView mv = new ModelAndView();
		mv.setViewName("frm/workflow/sample/business-task-tab");
		mv.addObject("tabInfo", "自定义标签2");

		log.info("跳转到业务自定义标签2");
		return mv;
	}

	@RequestMapping("/startProcessTravel")
	@ResponseBody
	public int startProcessTravel(TravelApplyEntity travelApplyEntity) {
		String processDefinitionKey = travelApplyEntity.getProcessDefinitionKey();// request.getParameter("processDefinitionKey");
		String assignee = travelApplyEntity.getAssigneeDz();// request.getParameter("assignee");
		String taskDefinitionKey = travelApplyEntity.getTaskDefinitionKey();// request.getParameter("taskDefinitionKey");
		
		SysStaff staff = getSessionCache(R.UserSign.SIGNIN_USER_SESSION);
		int staffId = staff.getStaffId();
		travelApplyEntity.setApplyStaffId(staffId);
		/*
		 * 在控制层处理完参数后即可调用业务模块的服务层，并注意控制事务
		 */
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		travelApplyEntity.setApplyDate(df.format(new Date()));
		travelApplyEntity.setStatus("0");
		System.out.println("startProcess11111=" + processDefinitionKey+"=====assignee="+assignee+"===========taskDefinitionKey="+taskDefinitionKey);
		// 获取回传的值
		String proc_inst_id = elecBusinessService.startProcess(processDefinitionKey, assignee, taskDefinitionKey,
				travelApplyEntity);// 流程实例ID
		travelApplyEntity.setProcInstId(proc_inst_id);
		//int insertnum = dzghApplyService.addDzgh(travelApplyEntity);
		int insertnum = projApplyService.addTravel(travelApplyEntity);
		this.updateProcess(proc_inst_id, travelApplyEntity.getProjId(), taskDefinitionKey, "1", assignee, "0", "1");// 调用公共方法，更新流程信息
		return insertnum;// new JSONObject().element("sign", "success");
	}

	/**
	 * 流程推进参数说明
	 * 
	 * @param taskDefinitionKey
	 *            目标环节定义编码
	 * @param assignee
	 *            目标环节受理人
	 * @param processInstanceId
	 *            流程实例ID
	 * @param taskId
	 *            任务ID
	 * @param comment
	 *            处理意见
	 * @param handleType
	 *            处理类型，1通过，2回退
	 * @param withdraw
	 *            此次操作是否可逆，即推进后是否可退回
	 * @return 业务数据返回
	 */
	@RequestMapping("/pushProcess")
	@ResponseBody
	public JSONObject pushProcess(HttpServletRequest request) {
		String taskDefinitionKey = request.getParameter("taskDefinitionKey");
		String assignee = request.getParameter("assignee");
		String processInstanceId = request.getParameter("processInstanceId");
		String taskId = request.getParameter("taskId");
		String comment = request.getParameter("comment");
		int handleType = Integer.valueOf(request.getParameter("handleType"));
		int withdraw = Integer.valueOf(request.getParameter("withdraw"));

		/*
		 * 在控制层处理完参数后即可调用业务模块的服务层，并注意控制事务，此处仅示例，具体所需参数业务模块自行决定
		 */
		System.out.println("pushProcess11111=" + taskDefinitionKey);
		elecBusinessService.pushProcess(processInstanceId, taskId, taskDefinitionKey, assignee, handleType, withdraw,
				comment);
		this.updateProcess(processInstanceId, "", taskDefinitionKey, "1", assignee, "0", String.valueOf(handleType));// 调用公共方法，更新流程信息
		return new JSONObject().element("sign", "success");
	}

	@RequestMapping("/breakProcess")
	@ResponseBody
	public JSONObject breakProcess(String processInstanceId, String taskId, String comment) {
		elecBusinessService.breakProcess(processInstanceId, taskId, comment);

		return new JSONObject().element("sign", "success");
	}

	@RequestMapping("/withdrawProcess")
	@ResponseBody
	public JSONObject withdrawProcess(String processInstanceId, String taskId) {
		elecBusinessService.withdrawProcess(processInstanceId, taskId);

		return new JSONObject().element("sign", "success");
	}

	@Autowired
	public void setElecBusinessService(@Qualifier("elecBusinessService") ElecBusinessService elecBusinessService) {
		this.elecBusinessService = elecBusinessService;
	}

	/**
	 * 公共方法，更新流程信息
	 * 
	 * @param proc_inst_id
	 *            流程实例ID
	 * @param elec_id
	 *            案件编号
	 * @param task_id
	 *            任务ID
	 * @param can_back
	 *            是否可驳回
	 * @param do_staff_id
	 *            当前处理人
	 * @param status
	 *            状态
	 * @param action_type
	 *            操作方式 0:回退 1:通过
	 * @return
	 */
	private int updateProcess(String proc_inst_id, String elec_id, String task_id, String can_back, String do_staff_id,
			String status, String action_type) {
		Map<String, String> m = new HashMap<String, String>();
		m.put("proc_inst_id", proc_inst_id); // 流程实例ID
		m.put("elec_id", elec_id);// 案件编号
		m.put("task_id", task_id);// 任务ID
		m.put("can_back", "1");// 是否可驳回
		m.put("do_staff_id", do_staff_id);// 当前处理人
		String flow_status;// 环节状态 0：待提交 1：初审 2:复审 3：备案 4：终审
		switch (task_id) {
		case "usertask1":
			flow_status = "0";
			break;
		case "usertask2":
			flow_status = "1";
			break;
		case "usertask3":
			flow_status = "2";
			break;
		case "usertask4":
			flow_status = "3";
			break;
		case "usertask5":
			flow_status = "4";
			break;
		case "endevent1":
			flow_status = "5";
			status = "1";
			break;
		default:
			flow_status = "0";
			break;
		}
		m.put("status", status);// 状态 0：申请中 1:完成 2：作废
		m.put("flow_status", flow_status);
		m.put("action_type", action_type);
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		m.put("oper_date", df.format(new Date()));
		this.dzghApplyService.addProcessByStep(m);
		return dzghApplyService.updateProcess(m);
	}
}
